package org.example.spring_boot_jwt_login.controller;

import org.example.spring_boot_jwt_login.dto.AuthRequest;
import org.example.spring_boot_jwt_login.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/auth")
public class AuthController {

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private AuthenticationManager authenticationManager;

    // 1. 公开接口
    @GetMapping("/welcome")
    public String welcome() {
        return "欢迎！此接口无需认证即可访问。";
    }

    // 2. 登录接口
    @PostMapping("/login")
    public String authenticateAndGetToken(@RequestBody AuthRequest authRequest) {
        Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(authRequest.getUsername(), authRequest.getPassword())
        );
        if (authentication.isAuthenticated()) {
            return jwtUtil.generateToken(authRequest.getUsername());
        } else {
            throw new UsernameNotFoundException("无效的用户请求！");
        }
    }

    // 3. 受保护接口 (需要登录)
    @GetMapping("/user/profile")
    public String userProfile() {
        return "这是受保护的用户个人信息（需 Token 访问）。";
    }

    // 4. 管理员接口 (需要 ADMIN 角色)
    @GetMapping("/admin/data")
    public String adminData() {
        return "这是管理员专属数据。";
    }
}